import { Service } from 'egg';
// import * as path from 'path';
import * as fs from 'fs';
import * as sendToWormhole from 'stream-wormhole';
import Result from '../utils/Result';
import * as pump from "pump"
import * as moment from "moment"
import * as path from "path";
// const awaitWriteStream = require('await-stream-ready').write;

/**
 * Test Service
 */
export default class File extends Service {

  /**
   * 文件上传
   */
  public async fileUpload() {
    const { ctx } = this;

    let parts:any = ctx.multipart({ autoFields: true });
    let files:any = [];
    let stream;
    // 循环获取数据流
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        // 多文件上传时，只能break,不能return
        break;
      }

      // 文件名，实际项目中文件名要添加时间戳
      let filename = stream.filename;

      // 拼接上传路径
      const upload_path = 'app' + ctx.app.config.UPLOAD_PATH + filename;

      // 读取文件 && 写入 && 销毁当前流
      await sendToWormhole(stream);
      try {
        // 创建可写流
        const writeStream = fs.createWriteStream(upload_path)
        // 读取文件 && 写入 && 销毁当前流
        await pump(stream, writeStream)
      } catch (err) {
        console.log(err)
      }
      // 存入数据库中
      const res = await ctx.app.model.File.create({
        url: ctx.app.config.UPLOAD_PATH + filename,
        fileName:filename,
        type:stream.mimeType
      });
      const data = res.get('', { plain: true });

      files.push(data)
    }
    if(files && files.length > 1){
      return Result.setData({
        code: 0,
        msg: '文件上传成功',
        data:files,
      });
    }else {
      return Result.setData({
        code: 0,
        msg: '文件上传成功',
        data:files[0],
      });
    }

    // // 读取表单提交的文件流
    // const stream = await ctx.getFileStream();
    //
    // // 获取上传的文件名  like.jpg dog.png
    // const file_name = stream.filename;
    //
    // // 拼接上传路径
    // const upload_path = 'app' + ctx.app.config.UPLOAD_PATH + file_name;
    // // 创建一个可以写入的流
    // const writeStream = fs.createWriteStream(upload_path);
    //
    // try {
    //   // 把读取到的表单信息流写入创建的可写流
    //   await awaitWriteStream(stream.pipe(writeStream));
    // } catch (err) {
    //   // 上传失败销毁流
    //   await sendToWormhole(stream);
    //   return Result.setData({
    //     code: 1,
    //     msg: '文件上传失败',
    //   });
    // }
    //
    // // 存入数据库中
    // const res = await ctx.app.model.File.create({
    //   url: ctx.app.config.UPLOAD_PATH + file_name,
    //   fileName:file_name,
    //   type:stream.mimeType
    // });
    // const data = res.get('', { plain: true });
    // return Result.setData({
    //   code: 0,
    //   msg: '文件上传成功',
    //   data,
    // });
  }

  /**
   * 阿里云文件上传
   */
  public async fileAlossUpload(){
    const { ctx } = this;

    let parts:any = ctx.multipart({ autoFields: true });
    let files:any = [];
    let stream;
    // 循环获取数据流
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        // 多文件上传时，只能break,不能return
        break;
      }

      // 文件名，实际项目中文件名要添加时间戳
      let filename = stream.filename;

      // 读取文件 && 写入 && 销毁当前流
      await sendToWormhole(stream);
      let result;
      try {
        result = await ctx.oss.putStream(`${moment().format("YYYY/MM/DD")}/${filename}`, stream);
      } catch (err) {
        console.log(err)
      }
      console.log(result);
      // 存入数据库中
      const res = await ctx.app.model.File.create({
        url: result?.url,
        fileName:filename,
        type:stream.mimeType
      });
      const data = res.get('', { plain: true });

      files.push(data)
    }
    if(files && files.length > 1){
      return Result.setData({
        code: 0,
        msg: '文件上传成功',
        data:files,
      });
    }else {
      return Result.setData({
        code: 0,
        msg: '文件上传成功',
        data:files[0],
      });
    }
  }

  /**
   * 获取下载文件
   */
  public async getFile(){
    const {ctx} = this;
    const getDataOne:any = await ctx.model.File.findOne({
      where: {
        id:ctx.params.id
      },
      raw: true,
    });
    if(!getDataOne) {
      return Result.setData({
        code:1,
        msg:"文件不存在"
      })
    }
    const flag = /(http|https):\/\/\S*/.test(getDataOne.url)
    ctx.logger.info(getDataOne)
    if(flag){
      const res = await this.ctx.curl(getDataOne.url, {
        streaming: true,
      });
      ctx.attachment(getDataOne.fileName);
      ctx.set('Content-Type', getDataOne.type);
      return res.res
    }else{
      const filePath = path.resolve('app' + ctx.app.config.UPLOAD_PATH, getDataOne.fileName);
      ctx.attachment(getDataOne.fileName);
      ctx.set('Content-Type', getDataOne.type);
      return fs.createReadStream(filePath);
    }
  }
}
